package com.woniu.order.app.components;

import com.woniu.exception.LXLGException;
import com.woniu.result.CommonResultCode;
import com.woniu.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class) //系统异常
    public Result handleException(Exception e) {
        log.error("执行出错", e);
        if (e instanceof DuplicateKeyException) {
            return Result.getInstance().setCode(501).setMsg( "数据库失败");
        }

        return Result.getInstance(CommonResultCode.GENERAL_FAIL);
    }

    @ExceptionHandler(LXLGException.class) //业务异常
    public Result handleAppException(LXLGException e) {

        log.warn("出现业务异常:" + e.getMessage(), e);
        return Result.getInstance().setCode(e.getCode()).setMsg( e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleBindException(MethodArgumentNotValidException e) {

        StringBuilder errorMsgBuilder = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            errorMsgBuilder.append(fieldError.getField() + ":" + fieldError.getDefaultMessage() + ";");
        }

        return Result.getInstance(CommonResultCode.INVALID_PARAM);
    }
}
